<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br />
    <el-card>
      <div class="header">
        <el-input
          placeholder="请输入内容"
          style="width: 400px"
          v-model="queryInfo.query"
          clearable
          @clear="getUserList"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserList"
          ></el-button>
        </el-input>
        <el-button
          type="primary"
          @click="addDialogVisible = true"
          style="margin-left: 20px"
          >添加用户</el-button
        >
      </div>

      <!-- 表格内容区域 -->
      <div class="table_content">
        <el-table style="width: 100%" :data="userList">
          <!-- 编号 这里的序号用索引index来实现 因为索引永远都是从0开始 所以给他加个1-->
          <el-table-column label="序号" align="center">
            <template v-slot="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <!-- 用户名 -->
          <el-table-column prop="username" label="姓名" align="center">
          </el-table-column>
          <!-- 邮箱 -->
          <el-table-column prop="email" label="邮箱" align="center">
          </el-table-column>
          <!-- 电话 -->
          <el-table-column prop="mobile" label="电话" align="center">
          </el-table-column>
          <!-- 角色权限 -->
          <el-table-column prop="role_name" label="角色权限" align="center">
          </el-table-column>
          <!-- 状态 -->
          <el-table-column prop="mg_state" label="状态" align="center">
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column fixed="right" label="操作" align="center">
            <template v-slot="scope">
              <!-- 编辑按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
              <!-- 删除 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
              <!-- 分配角色 -->
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部页面切换区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[4, 8, 12, 15]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

    </el-card>
  <!-- 添加用户对话框 -->
    <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        @close="addDialogClosed"
      >
        <!-- 表单区域 对话框里面是一个表单-->
        <!-- :model 表单对象 最终我们要提交的那个表单对象 -->
        <!-- :rules 表单验证的规则 -->
        <!-- ref  最终通过ref找到这张表单 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <!-- 手机 -->
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogClosed">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>

      <!-- 编辑用户对话框 -->
    <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        @close="editDialogClosed"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogClosed">取 消</el-button>
          <el-button type="primary" @click="editUserInfo"
            >确 定</el-button
          >
        </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed">
      <div>
        <p>当前用户:{{roleInfo.username}}</p>
        <p>当前的角色:{{roleInfo.role_name}}</p>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };

    //验证手机号的正则
    var checkMobile = (rule, value, cb) => {
      //验证手机号的正则
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号码"));
    };

    return {
      //添加用户的规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3-10个字符之间",
            trigger: "blur",
          },
        ],

        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在6-15个字符之间",
            trigger: "blur",
          },
        ],

        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],

        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      //编辑用户规则
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],

        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //表单对象 对应表单里会出现的选项 然后上面已经v-model双向绑定 填了就有值
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addDialogVisible: false,
      editDialogVisible: false,
      setRoleDialogVisible:false,
      //用来代替这次get请求要带的参数给
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 8,
      },
      menulist: [],
      userList: [],
      // 下拉选中的角色id值
      selectedRoleId:'',
      // 需要被分配角色的用户信息
      roleInfo:{},
      // 所有角色的数据列表
      roleList:{},
      //查询到的用户信息对象表格
      editForm: {},
      total: 0,
    };
  },
  methods: {
    //ajax请求用户数据
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.$message.success("获取用户列表成功");
      this.userList = res.data.users;
      this.total = res.data.total;
      // console.log(res);
    },

    async userStateChanged(userinfo) {
      // console.log(userinfo)
      // const {data:res} = await this.$http.put("users/${userinfo.id}/state/${userinfo.mg_state}")
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      // console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },

    //分页栏功能（点击后能改变显示的页面条数大小）
    //他这里方法自带实现 你一点击对应的分页条数 他就赋值它给size 就有值了
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.queryInfo.pagenum = 1; // 在改变每页显示的条数时，要将页码显示到第一页
      this.getUserList(); // 分页请求数据
    },

    // 分页--点击页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 提交添加用户的数据
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.addDialogClosed();
        this.getUserList();
      });
    },

    //点击编辑按钮
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败！");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },

    //提交编辑用户的信息
    editUserInfo(){
      this.$refs.editFormRef.validate(async (valid) =>{
        if(!valid) return;
        const{data:res}=await this.$http.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile,
        })
        if(res.meta.status !== 200){
          return this.$message.error('更新用户信息失败')
        }
        this.editDialogVisible= false
        this.getUserList()
        this.$message.success('更新用户信息成功')

      })
    },

    // 关闭模态框 调用表单重置的方法
    addDialogClosed() {
      // 重置表单
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields();
    },
    // 关闭模态框 调用表单重置的方法
    editDialogClosed() {
      // 重置表单
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
    },

    // 根据id删除操作
    async deleteUser(id){
      const confirmResult =await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmResult !== 'confirm'){
          return this.$message.info('已取消删除')
        }
        const {data: res} = await this.$http.delete('users/' + id)
        if(res.meta.status !== 200){
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getUserList()

    },
    // 分配权限操作
    async setRole(roleInfo){
      this.roleInfo = roleInfo
      
      // 展示对话框前 获取所有角色的列表
      const{data :res} = await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 用户界面点击按钮分配权限
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$message.error('请选择要分配的角色！')
      }
      const {data :res} = await this.$http.put(`users/${this.roleInfo.id}/role`,{
        rid:this.selectedRoleId
      })
      if(res.meta.status !== 200){
      return this.$message.error('更新角色失败')
    }
    this.$message.success('更新角色成功')
    this.getUserList()
    this.setRoleDialogVisible = false
    },
    // 用户列表分配角色关闭事件
    setRoleDialogClosed(){
      this.selectedRoleId= ''
      this.userInfo = ''
    },

    
  },

  created() {
    this.getUserList();
  },
};
</script>

<style scoped>
.pagination {
  /* 让该元素变为绝对定位，即对于浏览器窗口来定位 默认为往左边靠*/
  /* position: fixed; */
  /* 当我们给bottom和right时，就相当于改元素在绝对右下角，然后可以设置距离值 */
  /* bottom: 25px;
  right: 10px; */
  margin-left: 800px;
  margin-top: 10px;
}
</style>